package com.evon.yardmanagement.dao.interceptor;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Date;

import org.apache.shiro.SecurityUtils;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import com.evon.yardmanagement.model.Auditable;

public class AuditInterceptor extends EmptyInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public boolean onFlushDirty(Object entity, Serializable id,
			Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {

		if (entity instanceof Auditable) {
			setValue(currentState, propertyNames, "updatedBy", SecurityUtils
					.getSubject().getPrincipal());
			setValue(currentState, propertyNames, "updatedDate", new Date());
		}
		return true;
	}

	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {

		if (entity instanceof Auditable) {
			setValue(state, propertyNames, "createdBy", SecurityUtils
					.getSubject().getPrincipal());
			setValue(state, propertyNames, "createdDate", new Date());
			setValue(state, propertyNames, "updatedBy", SecurityUtils
					.getSubject().getPrincipal());
			setValue(state, propertyNames, "updatedDate", new Date());
		}
		return true;

	}

	private void setValue(Object[] currentState, String[] propertyNames,

	String propertyToSet, Object value) {

		int index = Arrays.asList(propertyNames).indexOf(propertyToSet);

		if (index >= 0) {

			currentState[index] = value;

		}

	}
}
